<template>

  <div>
    <el-card class="box-card" v-for="(goodRule,index) in goodsRules" :key="index">
      <div slot="header" class="clearfix">
        <el-input v-model="goodRule.title" :ref="'goodsRuleInput'+index" placeholder="请输入商品规格名称(比如颜色)" style="width:250px;"></el-input>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <el-checkbox v-model="goodRule.hasPic" @change="changeHasPic(goodRule,index)">添加图片</el-checkbox>
        <i class="el-icon-close close-btn right-icon" @click="removeRule(index)"></i>
      </div>
      <div class="el-tag-wrapper" :key="yindex" v-for="(item,yindex) in goodRule.items">
        <el-tag closable :disable-transitions="false" class="my-el-tag" @close="handleClose(index,yindex)">
          {{item.title}}
        </el-tag>
        <el-upload v-if="goodRule.hasPic" class="avatar-uploader" :action="UPLOAD_URL" :show-file-list="false" :on-success="handleAvatarSuccess(item)"
            :before-upload="beforeAvatarUpload">
            <img v-if="item.cover" :src="item.cover|absUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <div class="el-tag-wrapper">
           <el-input class="input-new-tag" v-if="goodRule.inputVisible" v-model="goodRule.inputValue" :ref="'saveTagInput'+index" size="small"
        @keyup.enter.native="handleInputConfirm(index)" @blur="handleInputConfirm(index)" :focus="true">
      </el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput(index)">+ 添加规格</el-button>
      </div>
     
    </el-card>

    <el-button type="primary" size="small" icon="el-icon-plus" @click="addNewGoodRule">添加商品规格</el-button>
    <div class="price-and-stock" v-if="hasValidRules">
      <table>
        <thead>
          <tr>
            <th v-for="(goodRule,index) in goodsRules" :key="index" v-if="goodRule.items && goodRule.items.length">
              {{goodRule.title}}
            </th>
            <th width="120">市场价</th>
            <th width="120">微信价</th>
            <th width="120">积分价</th>
            <th width="120">库存</th>
            <th width="120">预警库存</th>
            <th width="120">商品编号</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row,index) in goodsRulePrices" :key="index">
            <td v-for="(value,field) in row" :key="field" v-if="value.rowSpan" :rowspan="value.rowSpan">
              {{value.title}}
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="marketPriceMap[row[row.length-1]]" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="priceMap[row[row.length-1]]" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="pointsMap[row[row.length-1]]" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="stockMap[row[row.length-1]]" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="warnStockMap[row[row.length-1]]" :min="0"></el-input-number>
            </td>
            <td>
              <input type="text" class="numberbox goods-no" v-model="goodsNoMap[row[row.length-1]]" size="mini">
            </td>
          </tr>
          <tr>
            <td :colspan="hasValidRules">批量修改</td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchMarketPrice" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchPrice" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchPoints" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchStock" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchWarnStock" :min="0"></el-input-number>
            </td>
            <td>
              <input type="text" class="numberbox goods-no" size="mini" v-model="batchGoodsNo">
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
export default {
  data() {
    return {
      batchGoodsNo: "",
      batchMarketPrice: 0,
      batchPoints: 0,
      batchStock: 0,
      batchWarnStock: 0,
      batchPrice: 0,

      goodsRules: [],
      pointsMap: {},
      marketPriceMap: {},
      priceMap: {},
      stockMap: {},
      warnStockMap: {},
      goodsNoMap: {}
    };
  },
  model: {
    prop: "goodsRuleValues",
    event: "changeGoodsRuleValues"
  },
  props: {
    goodsRuleValues: null
  },
  created() {
   
    this.initData();
  },
  watch: {
    goodsRuleValues() {
      this.initData();
    },
    batchPrice() {
      for (let key in this.priceMap) {
        if (this.priceMap.hasOwnProperty(key)) {
          this.priceMap[key] = this.batchPrice;
        }
      }
    },
    batchMarketPrice() {
      for (let key in this.marketPriceMap) {
        if (this.marketPriceMap.hasOwnProperty(key)) {
          this.marketPriceMap[key] = this.batchMarketPrice;
        }
      }
    },
    batchPoints() {
      for (let key in this.pointsMap) {
        if (this.pointsMap.hasOwnProperty(key)) {
          this.pointsMap[key] = this.batchPoints;
        }
      }
    },
    batchStock() {
      for (let key in this.stockMap) {
        if (this.stockMap.hasOwnProperty(key)) {
          this.stockMap[key] = this.batchStock;
        }
      }
    },
    batchWarnStock() {
      for (let key in this.warnStockMap) {
        if (this.warnStockMap.hasOwnProperty(key)) {
          this.warnStockMap[key] = this.batchWarnStock;
        }
      }
    },
    batchGoodsNo() {
      for (let key in this.goodsNoMap) {
        if (this.goodsNoMap.hasOwnProperty(key)) {
          this.goodsNoMap[key] = this.batchGoodsNo;
        }
      }
    }
  },
  computed: {
    hasValidRules() {
      let rt = 0;
      this.goodsRules.forEach(el => {
        if (el.items && el.items.length > 0) {
          rt++;
        }
      });
      return rt;
    },
    goodsRulePrices() {
      let rowCount = 0;
      for (let i = 0; i < this.goodsRules.length; i++) {
        if (this.goodsRules[i].items.length > 0) {
          if (rowCount == 0) {
            rowCount = 1;
          }
          rowCount *= this.goodsRules[i].items.length;
        }
      }
      let rows = [];
      if (rowCount > 0) {
        for (let i = 0; i < rowCount; i++) {
          rows.push([]);
        }
        let groupCount = 1; // 分组
        let colIndex = 0;
        for (let i = 0; i < this.goodsRules.length; i++) {
          let rule = this.goodsRules[i];
          let items = rule.items;
          if (items && items.length) {
            let rowSpan = rowCount / items.length / groupCount;
            let groupSize = rowCount / groupCount;
            for (let g = 0; g < groupCount; g++) {
              for (let j = 0; j < items.length; j++) {
                for (let k = 0; k < rowSpan; k++) {
                  rows[groupSize * g + j * rowSpan + k][colIndex] = {
                    title: items[j].title,
                    index: j,
                    rowSpan: k == 0 ? rowSpan : 0
                  };
                }
              }
            }
            groupCount *= items.length;
            colIndex++;
          }
        }
      }
      rows.forEach((row, rowIndex) => {
        let idx = this.priceIndex(row);
        idx in this.goodsNoMap || this.$set(this.goodsNoMap, idx, "");
        idx in this.stockMap || this.$set(this.stockMap, idx, 0);
        idx in this.priceMap || this.$set(this.priceMap, idx, 0);
        idx in this.pointsMap || this.$set(this.pointsMap, idx, 0);
        idx in this.warnStockMap || this.$set(this.warnStockMap, idx, 0);
        idx in this.marketPriceMap || this.$set(this.marketPriceMap, idx, 0);
        row.push(idx);
      });
      
      return rows;
    }
  },
  methods: {
    getData(){
      let data = {
        goodsRules: this.goodsRules,
        pointsMap: this.pointsMap,
        marketPriceMap: this.marketPriceMap,
        priceMap: this.priceMap,
        stockMap: this.stockMap,
        warnStockMap: this.warnStockMap,
        goodsNoMap: this.goodsNoMap
      };
      return data;
      // this.$emit("changeGoodsRuleValues", JSON.stringify(data));
    },
    initData() {
      let data = this.goodsRuleValues;
      // return;
      if (typeof data !== "string") {
        if (data) {
          this.goodsNoMap = data.goodsNoMap || {};
          data.goodsRules.forEach(el => {
            Vue.set(el, "inputVisible", false);
            Vue.set(el, "inputValue", "");
          });
          Vue.set(this.$data, "goodsRules", data.goodsRules);
          this.marketPriceMap = data.marketPriceMap || {};
          this.pointsMap = data.pointsMap || {};
          this.priceMap = data.priceMap || {};
          this.stockMap = data.stockMap || {};
          this.warnStockMap = data.warnStockMap || {};
        } else {
          this.goodsRules = [];
          this.pointsMap = {};
          this.marketPriceMap = {};
          this.priceMap = {};
          this.stockMap = {};
          this.warnStockMap = {};
          this.goodsNoMap = {};
        }
      }
    },
    changeHasPic(item, index) {
      if (item.hasPic) {
        this.goodsRules.forEach((el, idx) => {
          if (idx != index) {
            el.hasPic = false;
          }
        });
      }
    },
    handleAvatarSuccess(item) {
      return (res, file) => {
        if (res && res.errcode == 0) {
          item.cover = res.info;
        }
      };
    },
    priceIndex(row) {
      let rt = [];
      for (let i = 0; i < row.length; i++) {
        rt.push(row[i].index);
      }
      return rt.join(",");
    },
    addNewGoodRule() {
      if (this.goodsRules.length == 0) {
        this.$emit("hasNewGoodRules");
      }
      this.goodsRules.push({
        title: "",
        hasPic: false,
        inputVisible: false,
        inputValue: "",
        items: []
      });
      this.$nextTick(_ => {
        this.$refs["goodsRuleInput" + (this.goodsRules.length - 1)][0].focus();
      });
    },
    removeRule(index) {
      this.goodsRules.splice(index, 1);
      if (this.goodsRules.length == 0) {
        this.$emit("hasNoNewGoodRules");
      }
      this.goodsNoMap = {};
      this.stockMap = {};
      this.priceMap = {};
      this.pointsMap = {};
      this.warnStockMap = {};
      this.marketPriceMap = {};
    },
    handleClose(index, yindex) {
      this.goodsRules[index].items.splice(yindex, 1);
      if (this.goodsRules[index].items.length == 0) {
        this.goodsNoMap = {};
        this.stockMap = {};
        this.priceMap = {};
        this.pointsMap = {};
        this.warnStockMap = {};
        this.marketPriceMap = {};
      }
    },
    showInput(index) {
      this.goodsRules[index].inputVisible = true;
      // this.$set(this.goodsRules[index],'inputVisible',true);

      this.$nextTick(_ => {
        this.$refs["saveTagInput" + index][0].focus();
      });
    },

    handleInputConfirm(index) {
      let inputValue = this.goodsRules[index].inputValue;
      if (inputValue) {
        this.goodsRules[index].items.push({
          title: inputValue,
          cover: ""
        });
        if (this.goodsRules[index].items.length == 1) {
          this.goodsNoMap = {};
          this.stockMap = {};
          this.priceMap = {};
          this.pointsMap = {};
          this.warnStockMap = {};
          this.marketPriceMap = {};
        }
      }
      this.goodsRules[index].inputVisible = false;
      this.goodsRules[index].inputValue = "";
    }
  }
};
</script>


<style scoped>
.el-tag {
  width: 80px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: block;

  position: relative;
}

.el-tag >>> .el-tag__close {
  position: absolute;
  right: 5px;
  top: 7px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.el-tag-wrapper {
  display: inline-block;
  vertical-align: middle;
}
.el-tag-wrapper + .el-tag-wrapper {
  margin-left: 10px;
}
.avatar-uploader {
  margin-top: 5px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}

.goods-no {
  border: 1px solid #aaa;
  padding: 4px 6px;
  border-radius: 4px;
}

.box-card {
  margin-bottom: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.price-and-stock table {
  margin-top: 20px;
  width: 100%;
  border-collapse: collapse;
  text-align: center;
}

.price-and-stock th {
  border: 1px solid #eee;
}

.price-and-stock td {
  border: 1px solid #eee;
}

.numberbox {
  width: 100px;
}

.right-icon {
  float: right;
}

.close-btn {
  cursor: pointer;
  margin-top: 10px;
  font-size: 16px;
}

.close-btn:hover {
  color: #409eff;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
